package com.heima.interceptor;

import com.heima.common.thread.MyThreadLocal;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头的用户id
        String userId = request.getHeader("userId");
        // 判断是否存在
        if (userId == null){
            return false;
        }
        // 存在, 存入threadlocal
        MyThreadLocal.set(userId);
        // 放行
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        MyThreadLocal.remove();
    }
}
